<template>
  <div class="mall-order">
    <nav-bar></nav-bar>
    <div class="page-main" v-loading.body="loading">
      <div class="xyd-container xc1">
        <div class="xyd-c-title" style="text-align:left;padding:0 10px">
          收货信息
          <a href="javascript:;" @click="handleAdd">+编辑收货信息</a>
        </div>
        <div class="xyd-c-content">
          <ul class="tl-body-more" :style="spread ? `height: ${80 * address.length - 1}px` : 'height: 80px'">
            <li class="tl-item" v-for="item,i in address" :key="i">
              <label class="title">{{item.title}}</label>
              <span>{{item.name}}</span>
              <span>{{item.district}}</span>
              <span>{{item.address}}</span>
              <span>{{item.phone_no}}</span>
              <el-checkbox :value="item.checked" @change="changeAddrCheck(item)" @editfinish="handleFinish"></el-checkbox>
            </li>
          </ul>
          <div class="tl-bottom">
            <a href="javascript:;" @click="selectOther">
              <span v-if="!spread">更多地址<i class="el-input__icon el-icon-caret-bottom"></i></span>
              <span v-if="spread">收起<i class="el-input__icon el-icon-caret-top"></i></span>
            </a>
          </div>
        </div>
      </div>
      <div class="xyd-container xc2">
        <div class="xyd-c-title" style="text-align:left;padding:0 10px">
          支付信息
        </div>
        <div class="xyd-c-content">
          <ul>
            <li class="shop-item" v-for="item,i in product" :key="i">
              <div class="item-container">
                <div>{{item.shop_name}}</div>
                <ul>
                  <li class="commodity-item clearfix" v-for="child,j in item.product" :key="j">
                    <div class="img-container">
                      <img :src="child.pic"/>
                    </div>
                    <div class="title-intro">
                      <div class="title">{{child.title}}</div>
                      <div class="intro">{{child.intro | getSimpleText}}</div>
                    </div>
                    <div class="price">
                      ¥{{child.price}}
                    </div>
                    <div class="amount">
                      x{{child.amount}}
                    </div>
                    <div class="remarks">
                      有货
                    </div>
                  </li>
                </ul>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <div class="page-bottom">
        <div class="pp-c-top">
          <div class="pay-type">
            <label>选择支付方式：</label>
            <el-select v-model="pay_type" placeholder="请选择">
              <el-option
                v-for="item in pay_types"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          {{count}}件  商品，商品总金额：￥{{totalPrice | moneyFormat}}<br/>
          <!-- 优惠信息：￥0.00<br/> -->
          运费：￥{{total_freight}}<br/>
        </div>
        <div class="pp-c-bottom">
          <div>
            已选择 {{count}} 件商品     总价：
            <span class="money">¥ {{totalPrice + total_freight | moneyFormat}}</span>
          </div>
          <button class="orange-btn" @click="handleSubmitOrder">去支付</button>
        </div>
      </div>
    </div>
    <el-dialog title="编辑收获地址" top="20px" :visible.sync="dialogFormVisible" @close="handleAddr">
      <ul class="d-tl-body-more" >
        <li class="tl-item" v-for="item,i in address" :key="i">
          <addr-form :form="item" @change="changeAddrDefault"></addr-form>
          <!-- <el-form style="padding: 37px 80px 0">
            <el-form-item label="收货人姓名：" :label-width="'100px'">
              <el-input :value="item.name" auto-complete="off" ></el-input>
            </el-form-item>
            <el-form-item label="收货地址：" :label-width="'100px'">
              <el-input :value="item.district" auto-complete="off" ></el-input>
            </el-form-item>
            <el-form-item label="详细地址：" :label-width="'100px'">
              <el-input :value="item.address" auto-complete="off" ></el-input>
            </el-form-item>
            <el-form-item label="联系电话：" :label-width="'100px'">
              <el-input v-model="item.phone_no" auto-complete="off" ></el-input>
            </el-form-item>
            <el-form-item>
              <el-checkbox :value="item.is_default" @change="changeAddrDefault(item)" style="margin-right: 15px;">设为默认地址</el-checkbox>
              <el-button type="primary" size="small" @click="handlePreserve('edit', item)">保存</el-button>
              <el-button size="small" @click="handleDelete('edit', item)">删除</el-button>
            </el-form-item>
          </el-form> -->
        </li>
      </ul>
      <!-- <el-form style="padding: 37px 80px 0" v-if="JSON.stringify(newAddr) !== '{}'">
        <el-form-item label="收货人姓名：" :label-width="'100px'">
          <el-input :value="newAddr.name" auto-complete="off" ></el-input>
        </el-form-item>
        <el-form-item label="收货地址：" :label-width="'100px'">
          <el-input :value="newAddr.district" auto-complete="off" ></el-input>
        </el-form-item>
        <el-form-item label="详细地址：" :label-width="'100px'">
          <el-input :value="newAddr.address" auto-complete="off" ></el-input>
        </el-form-item>
        <el-form-item label="联系电话：" :label-width="'100px'">
          <el-input :value="newAddr.phone_no" auto-complete="off" ></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox :value="newAddr.is_default" @change="changeAddrDefault(newAddr)">设为默认地址</el-checkbox>
          <el-button type="primary" size="small">保存</el-button>
          <el-button size="small">删除</el-button>
        </el-form-item>
      </el-form> -->
      <div style="text-align: center;margin-top: 20px;">
        <el-button @click="addNewAddr">新增地址</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { NavBar } from 'views/layout'
import { getOrder, addAddr, editAddr, submitOrder, submitNow, getAddr } from 'api/shop'
import addrForm from 'views/components/addrForm'

export default {

  name: 'order',
  components: {
    NavBar,
    addrForm
  },
  data() {
    return {
      product: [],
      address: [],
      pay_type: '',
      pay_types: [
        { label: '支付宝', value: 0 },
        { label: '微信支付', value: 1 }
      ],
      /* defaultAddr: {},
      notDefaultAddr: [], */
      dialogFormVisible: false,
      count: 0,
      totalPrice: 0,
      total_freight: 0,
      spread: false,
      loading: false
    };
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取数据
    fetchData() {
      this.loading = true
      const { type, pic, title, intro, price, freight, shop_id, shop_name, amount } = this.$route.query
      const { ids } = this.$route.params
      if (ids == 0) {
        console.log(pic, title, intro, price, freight, shop_id, shop_name, amount)
        this.product = [
          {
            freight,
            shop_name,
            product: [
              {
                amount,
                freight,
                intro,
                pic,
                price,
                shop_id,
                title
              }
            ]
          }
        ]
        this.total_freight = freight ? Number(freight) : 0
        for (let i = 0; i < this.product.length; i++) {
          const child = this.product[i].product
          for (let j = 0; j < child.length; j++) {
            this.count++
            this.totalPrice += Number(child[j].price) * child[j].amount
          }
        }
        getAddr()
        .then(res => {
          this.loading = false
          this.address = res.data.map(v => {
            if (v.is_default) {
              this.checkedAddr = v.id
            }
            v.checked = v.is_default
            return v
          })
        })
        .catch(err => {
          this.loading = false
          console.log(err)
        })
      } else {
        getOrder({
          item: ids,
          p: type
        })
        .then(res => {
          this.loading = false
          this.product = res.data.product
          // 设置选中地址
          this.address = res.data.address.map(v => {
            if (v.is_default) {
              this.checkedAddr = v.id
            }
            v.checked = v.is_default
            return v
          })
          this.total_freight = res.data.total_freight ? Number(res.data.total_freight) : 0
          // 数量与价格计算
          for (let i = 0; i < this.product.length; i++) {
            const child = this.product[i].product
            for (let j = 0; j < child.length; j++) {
              this.count++
              this.totalPrice += Number(child[j].price) * child[j].amount
            }
          }
        })
        .catch(err => {
          this.loading = false
          console.log(err)
        })
      }
    },
    // 编辑弹框
    handleAdd() {
      this.dialogFormVisible = true
      // editAddr({
      //   aid: 2,
      //   is_default: false
      // })
      // .then(res => console.log(res))
      // .catch(err => console.log(err))
    },
    // 更改默认地址
    changeAddrDefault(item) {
      console.log(item)
      this.address.forEach(v => {
        if (v.is_default) {
          v.is_default = false
          editAddr({
            aid: v.id,
            is_default: 0
          })
          .then(res => console.log(res))
          .catch(err => console.log(err))
        }
      })
      item.is_default = !item.is_default
      editAddr({
        aid: item.id,
        is_default: item.is_default ? 1 : 0
      })
      .then(res => console.log(res))
      .catch(err => console.log(err))
    },
    // 下拉，查看更多地址
    selectOther() {
      this.spread = !this.spread
    },
    // 选择收货地址
    changeAddrCheck(item) {
      console.log(this.address)
      this.address.forEach(v => {
        if (v.id === item.id) {
          this.checkedAddr = item.id
          v.checked = true
        } else {
          v.checked = false
        }
      })
    },
    // 提交订单
    handleSubmitOrder() {
      const { type, pid, amount, shop_id, price_id } = this.$route.query
      const { ids } = this.$route.params
      const product = this.product.map(v => {
        const p = {
          shop: v.shop,
          item: v.product.map(v => v.item).join(',')
        }
        return p
      })
      if (this.pay_type === '') {
        this.$message({
          message: '请选择支付方式',
          type: 'warning'
        })
        return false
      }
      if (this.checkedAddr === '') {
        this.$message({
          message: '请选择收货地址',
          type: 'warning'
        })
        return false
      }
      if (ids == 0) { // 立即购买下订单
        submitNow({
          addr: this.checkedAddr,
          total: this.totalPrice.toFixed(2),
          product: pid,
          shop: shop_id,
          amount,
          pu: type == 1 ? price_id : null,
          platform: type,
          pay_type: this.pay_type
        })
        .then(res => {
          if (res.pay_url) {
            location.href = res.pay_url
          } else {
            this.$message({
              message: '支付链接为空',
              type: 'warning'
            })
          }
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: 'error'
          })
        })
      } else { // 下订单
        submitOrder({
          addr: this.checkedAddr,
          total: this.totalPrice.toFixed(2),
          product: JSON.stringify(product),
          platform: type,
          pay_type: this.pay_type
        })
        .then(res => {
          if (res.pay_url) {
            location.href = res.pay_url
          } else {
            this.$message({
              message: '支付链接为空',
              type: 'warning'
            })
          }
          // window.open(res.pay_url)
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: 'error'
          })
        })
      }
    },
    // 关闭前回调，重新渲染
    handleAddr() {
      this.fetchData()
    },
    handleFinish() {
      this.fetchData()
    },
    // 添加地址
    addNewAddr() {
      const newAddr = {
        title: '',
        name: '',
        district: '',
        address: '',
        phone_no: '',
        is_default: false,
        checked: false
      }
      this.address = this.address.concat(newAddr)
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import '../../styles/mixin.scss';
.mall-order{
  .page-main{
    width: 1200px;
    margin: 0 auto;
    .xc1{
      .xyd-c-title{
        a{
          float: right;
          font-size: 12px;
          color: #00A2EA;
        }
      }
      .xyd-c-content{
        .tl-bottom{
          text-align: center;
          line-height: 30px;
          >a{
            position: relative;
            padding-right: 30px;
          }
        }
        .tl-item{
          height: 80px;
          line-height: 80px;
          padding: 0 35px;
          >label.title{
            border: 1px solid #00BAB0;
            color: #00BAB0;
            padding: 5px;
            border-radius: 2px;
          }
        }
        .tl-body-more{
          overflow: hidden;
          transition: height .2s;
          .tl-item{
            height: 80px;
            line-height: 80px;
            padding: 0 35px;
            >label.title{
              border: 1px solid #00BAB0;
              color: #00BAB0;
              padding: 5px;
              border-radius: 2px;
            }
            >span{
              margin-left: 15px;
            }
          }
        }
      }
    }
    .xc2{
      .xyd-c-content{
        .shop-item{
          padding: 0 35px;
          .item-container{
            padding: 35px 0;
            border-bottom: 1px solid #e5e6e7;
            .commodity-item{
              padding: 20px 0;
              &:last-child{
                border: none;
              }
              >div{
                float: left;
                &.img-container{
                  width: 90px;
                  height: 90px;
                  border: 1px solid #e5e6e7;
                  >img{
                    width: 100%;
                    height: 100%;
                  }
                }
                &.title-intro{
                  width: 270px;
                  margin-left: 20px;
                  .title{
                    font-size: 16px;
                    font-weight: bold;
                    color: #333;
                  }
                  .intro{
                    color: #999;
                    @include ellipsisLn(3)
                  }
                }
                &.price{
                  width: 200px;
                  text-align: center;
                  color: #E66306;
                  font-size: 16px;
                }
                &.amount{
                  width: 200px;
                  text-align: center;
                }
                &.remarks{
                  width: 100px;
                  text-align: center;
                  color: #999;
                }
              }
            }
          }
        }
      }
    }
    .page-bottom{
      position: relative;
      .pp-c-top{
        text-align: right;
        line-height: 30px;
        position: relative;
        .pay-type{
          position: absolute;
          left: 0;
          top: 10px;
          >label{
            font-weight: bold;
          }
        }
      }
      .pp-c-bottom{
        position: relative;
        // bottom: 0;
        // left: 0;
        // right: 0;
        height: 50px;
        background-color: #eee;
        >div{
          position: absolute;
          right: 180px;
          top: 16px;
          .money{
            color: #E66306;
          }
        }
        >button{
          position: absolute;
          right: 0;
          top: 0;
          bottom: 0;
          width: 170px;
          height: 50px;
          font-size: 16px;
        }
      }
    }
  }
}
.d-tl-body-more{
  .tl-item{
    border-bottom: 1px solid #e5e6e7;
  }
}
</style>